package com.book.intercepter;

import cn.hutool.core.util.ObjectUtil;
import com.book.auth.IgnoreAuth;
import com.book.auth.UnauthorizedException;
import com.book.common.constant.CommonConstants;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserAuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 检测不拦截的方法
        IgnoreAuth annotation = handlerMethod.getBeanType().getAnnotation(IgnoreAuth.class);
        if (null == annotation) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreAuth.class);
            if (null == annotation) {
                if (ObjectUtil.isNull(request.getHeader(CommonConstants.USERHEAD))) {
                    throw new UnauthorizedException("未登录");
                }
            }
        }
        if (null != annotation) {
            return super.preHandle(request, response, handler);
        }

        if (ObjectUtil.isNotNull(request.getHeader(CommonConstants.USERHEAD))) {
//            String userId = DECHelper.decrypt(request.getHeader(CommonConstants.USERHEAD), Charset.forName("gb2312"), CommonConstants.USERHEAD);
//            BaseContextHandler.setUserId(userId);
        }

        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

}
